<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h3>登录</h3>
      </template>
      <el-form :model="loginForm" ref="loginFormRef" label-width="80px" @submit.prevent="handleLogin">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ElMessage} from 'element-plus';
import {ref} from "vue";
import router from "@/config/router";
import httpRequest from "@/config/request";
import store from "@/config/store";
// 表单数据
const loginForm = ref({
  username: 'admin',
  password: 'admin'
});
// 表单引用
const loginFormRef = ref(null);
// 登录处理函数
const handleLogin = async () => {
  if (loginForm.value.username === '' || loginForm.value.password === '') {
    ElMessage.error('用户名和密码不能为空');
    return;
  }
  try {
    // 调用接口
    const response = await httpRequest.post('user/login', loginForm.value);
    const {menus, permissionCodes, token, user} = response.data;
    //存储到userStore
    await store.dispatch("updateUser", user)
    await store.dispatch("updatePermissionCodes", permissionCodes)
    await store.dispatch("updateToken", token)
    await store.dispatch("updateMenus", menus)
    sessionStorage.setItem("menus", JSON.stringify(menus))
    sessionStorage.setItem("token", JSON.stringify(token))
    ElMessage.success('登录成功');
    await router.push("/");
  } catch (error) {
    ElMessage.error(error.msg);
  }
};

// 重置表单函数
const resetForm = () => {
  if (loginFormRef.value) {
    loginFormRef.value.resetFields();
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 450px;
}
</style>    